//
//  HDImagesZoomView.m
//  HDecoration
//
//  Created by koki on 15-4-25.
//  Copyright (c) 2015年 MyShare. All rights reserved.
//


#define kTimeInterval 4

#import "HDImagesSkimView.h"

@interface HDImagesSkimView ()
{
    NSTimer* timer;
    CGFloat _originalHeight;
    UIImageView *_bgImg;
}
@end

@implementation HDImagesSkimView
@synthesize index,pageCtr,m_TableView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self _initView];
        _originalHeight = frame.size.height;
        self.backgroundColor = [UIColor clearColor];
    }

    return self;
}

- (void)_initView
{
    _disableCirculate = NO;//默认循环
    _bgImg = [[UIImageView alloc] initWithFrame:self.bounds];
    _bgImg.image = [UIImage imageNamed:@"ic_no_img_detail.jpg"];
    [self addSubview:_bgImg];
    
    m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.height, self.width)
                                               style:UITableViewStylePlain];
    m_TableView.hidden = YES;
    m_TableView.delegate = self;
    m_TableView.scrollsToTop = NO;
    m_TableView.dataSource = self;
    m_TableView.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
    m_TableView.showsVerticalScrollIndicator = NO;
    m_TableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    m_TableView.pagingEnabled = YES;
    m_TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    m_TableView.backgroundView = nil;
    //m_TableView.backgroundColor = [UIColor blackColor];
    m_TableView.bounces = NO;//默认循环就去掉弹性
    [self addSubview:m_TableView];
    
    
    pageCtr = [[MSPageControl alloc] init];
    pageCtr.frame = CGRectMake(0,self.height-30, self.width, 20);
    pageCtr.pageIndicatorTintColor=[UIColor colorWithWhite:1 alpha:0.6];
    pageCtr.currentPageIndicatorTintColor=[UIColor whiteColor];
    pageCtr.enabled = NO;
    [self insertSubview:pageCtr aboveSubview:m_TableView];
    
    _tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width-55, self.height-30, 45, 20)];
    _tagLabel.textColor = [UIColor whiteColor];
    _tagLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:13];
    _tagLabel.textAlignment = NSTextAlignmentCenter;
    _tagLabel.layer.shadowOffset=CGSizeMake(0.5, 0.5);
    _tagLabel.layer.shadowColor=[UIColor blackColor].CGColor;
    _tagLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    _tagLabel.layer.cornerRadius = 10;
    _tagLabel.clipsToBounds = YES;
    _tagLabel.hidden = YES;
    [self insertSubview:_tagLabel aboveSubview:m_TableView];
    
    self.clipsToBounds=YES;
}

-(void)reloadData
{
   [m_TableView reloadData];
}

- (void)setDataArray:(NSArray *)imageArr
{
    _dataArray = imageArr;
    m_TableView.hidden = !imageArr.count;
    [m_TableView reloadData];
    pageCtr.numberOfPages = imageArr.count;
    CGSize pointSize = [pageCtr sizeForNumberOfPages:imageArr.count];
    CGFloat pageCtrlLeft = (self.width-pointSize.width)/2.0;
    if (self.pageControlAlignment==PageControlAlignmentLeft) {
        pageCtrlLeft = 20;
    } else if (self.pageControlAlignment==PageControlAlignmentRight) {
        pageCtrlLeft = self.width-pointSize.width-20;
    }
    pageCtr.frame = CGRectMake(pageCtrlLeft, pageCtr.top, pointSize.width, pageCtr.height);
    pageCtr.currentPage = 0;
    index=0;
    NSInteger firstFigure = MIN(imageArr.count, 1);
    _tagLabel.text = [NSString stringWithFormat:@"%ld/%zi",firstFigure,imageArr.count];
    if (_dataArray.count>1) {
        m_TableView.bounces = YES;
        if (!_disableCirculate) {//能循环
            NSIndexPath *indexPath =  [NSIndexPath indexPathForRow:index+1 inSection:0];
            [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
        else{
            NSIndexPath *indexPath =  [NSIndexPath indexPathForRow:index inSection:0];
            [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
        [self restartTimer];
    }
    else{
        m_TableView.bounces = NO;
    }
    if (!_disableCirculate) {//能循环的时候关闭弹性
        m_TableView.bounces = NO;
    }
}

- (void)setEnableCountTag:(BOOL)enableCountTag
{
    _enableCountTag = enableCountTag;
    _tagLabel.hidden = !enableCountTag;
}

- (DOImageView *)getImageViewForIndex:(NSInteger)cellIndex
{
    if (self.dataArray.count>cellIndex)
    {
        ImgItemCell *cell = [self.m_TableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
        return cell.skimImgView;
    }
    return [[DOImageView alloc] init];
}

-(void)restartTimer
{
    if (self.disableTimer)
    {
        return;
    }
    if (timer!=nil)
    {
        [timer invalidate];
        timer=nil;
    }
    timer=[NSTimer timerWithTimeInterval:kTimeInterval target:self selector:@selector(autoSkimImgView) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}


-(void)autoSkimImgView
{
    if (_disableCirculate) {
        return;
    }
    if (!self.dataArray.count) {
        return;
    }
    if (index==(self.dataArray.count-1))
    {
        
        NSIndexPath *indexPath =  [NSIndexPath indexPathForRow:index+2 inSection:0];
        [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        index=0;
        
        [self performBlock:^{
            NSIndexPath *indexPath =  [NSIndexPath indexPathForRow:index+1 inSection:0];
            [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        } afterDelay:0.3];
    }
    else
    {
        index+=1;
        NSIndexPath *indexPath =  [NSIndexPath indexPathForRow:index+1 inSection:0];
        [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    pageCtr.currentPage = index;
    _tagLabel.text = [NSString stringWithFormat:@"%zi/%zi",index+1,self.dataArray.count];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if ([self.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
    {
        [self.delegate performSelector:@selector(tableView:didSelectRowAtIndexPath:) withObject:tableView withObject:indexPath];
    }
    if (self.delegate &&[self.delegate respondsToSelector:@selector(imagesSkimView:tappedIndex:)])
    {
        [self.delegate imagesSkimView:self tappedIndex:self.index];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count>1 && !_disableCirculate)
    {
        return self.dataArray.count+2;
    } else {
        return self.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *idty = @"imgshowCell";
    ImgItemCell *cell = [tableView dequeueReusableCellWithIdentifier:idty];
    if (nil == cell)
    {
        cell = [[ImgItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idty];
        cell.contentView.transform = CGAffineTransformMakeRotation(M_PI / 2);
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.rect = self.bounds;
    cell.imgName = nil;
    propertyPicture* picInfo;
    if (_disableCirculate) {
        picInfo = self.dataArray[indexPath.row];
    }else{
        if (indexPath.row==0)
        {
            picInfo=[self.dataArray objectAtIndex:self.dataArray.count-1];
        }
        else if (indexPath.row==self.dataArray.count+1)
        {
            picInfo=[self.dataArray objectAtIndex:0];
        }
        else
        {
            picInfo=[self.dataArray objectAtIndex:indexPath.row-1];
        }
    }
    
    cell.imgName = picInfo.path;
    
    if (!_disableCirculate) {
        if(indexPath.row>index && indexPath.row<=index+2)
        {
            if (indexPath.row<self.dataArray.count)
            {
                [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section]];
            }
        }
        else if(indexPath.row<=index && indexPath.row>=index-2)
        {
            if (indexPath.row>0)
            {
                [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]];
            }
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.frame.size.width;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSIndexPath *indexPath =  [m_TableView indexPathForRowAtPoint:scrollView.contentOffset];

    if (_disableCirculate) {
        index = indexPath.row;
        pageCtr.currentPage = index;
        _tagLabel.text = [NSString stringWithFormat:@"%zi/%zi",index+1,self.dataArray.count];
        return;
    }
    
    if (indexPath.row==0)
    {
        index=self.dataArray.count-1;
        indexPath =  [NSIndexPath indexPathForRow:index+1 inSection:0];
        [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    else if (indexPath.row==self.dataArray.count+1)
    {
        index=0;
        indexPath =  [NSIndexPath indexPathForRow:index+1 inSection:0];
        [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    else
    {
        index=indexPath.row-1;
    }
    pageCtr.currentPage = index;
    _tagLabel.text = [NSString stringWithFormat:@"%zi/%zi",index+1,self.dataArray.count];
    [self restartTimer];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (timer && [timer isValid]) {
        [timer invalidate];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self restartTimer];
}

-(void)removeObserver
{
    [_anchorScrollView removeObserver:self forKeyPath:@"contentOffset"];
}

- (void)setAnchorScrollView:(UIScrollView *)anchorScrollView
{
    [_anchorScrollView removeObserver:self forKeyPath:@"contentOffset"];
    _anchorScrollView = anchorScrollView;
    _anchorScrollView.scrollsToTop = NO;
    [_anchorScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [self resignFirstResponder];
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.anchorScrollView)
    {
        CGFloat offsetY = _anchorScrollView.contentOffset.y;
        if (offsetY<=0 && -offsetY<=SCREENFRAME.size.height-_originalHeight)
        {
            if (!_anchorScrollView.decelerating) {
                UIEdgeInsets edgeInsets = UIEdgeInsetsMake(-offsetY, 0, 0, 0);
                _anchorScrollView.contentInset = edgeInsets;
            }
            self.top = offsetY;
            self.height = _originalHeight-offsetY;
            m_TableView.top = (self.height-m_TableView.height)/2.0;
            _tagLabel.top = self.height-30;
            pageCtr.top = self.height-45;
        }
    }
}

@end

@implementation ImgItemCell

- (void)dealloc {
    self.imgName = nil;
    self.skimImgView=nil;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self _initView];
    }
    return self;
}

-(void)setRect:(CGRect)rect
{
    _rect=rect;
    self.skimImgView.frame=rect;
}

- (void)_initView
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor=[UIColor clearColor];
    self.skimImgView = [[DOImageView alloc] initWithFrame:CGRectZero];
    self.skimImgView.imgURLStr = @"ic_no_img_detail";
    [self.contentView addSubview:self.imageView];
    self.clipsToBounds=NO;
    
    self.skimImgView.contentMode=UIViewContentModeScaleAspectFill;
    self.skimImgView.layer.masksToBounds = YES;
    [self.contentView addSubview:self.skimImgView];
}

- (void)setImgName:(NSString *)imgName
{
    _imgName=[imgName copy];

    if ([imgName rangeOfString:@"http://"].location == NSNotFound) {//不包含
        self.skimImgView.defaultImg=imgName;
    } else {//包含
        self.skimImgView.imgURLStr=imgName;
    }
}

@end








